import { createSlice } from '@reduxjs/toolkit'

const login = createSlice({
  name: "login",
  initialState: {
    num: 99,
    list: JSON.parse(sessionStorage.getItem('list')) || [],
    jilu: JSON.parse(sessionStorage.getItem('jilu')) || [],
  },
  reducers: {
    // 修复：支持增加/减少数量（通过type区分）
    addgwc(state, action) {
      const { id, type } = action.payload; // 接收id和操作类型（add/minus）
      const copyList = [...state.list];
      const index = copyList.findIndex(item => item.id === id);
      // 如果是减少数量，且当前数量>1才执行
      if (type === 'minus' && copyList[index].num > 1) {
        copyList[index].num--;
        copyList[index].orderAmount = copyList[index].price * copyList[index].num
      }
      // 如果是增加数量，直接+1
      if (type === 'add') {
        copyList[index].num++;
        copyList[index].orderAmount = copyList[index].price * copyList[index].num
      }
      state.list = copyList;
      sessionStorage.setItem('list', JSON.stringify(copyList));
    },
    addj(state, actions) {
      const copyList = [...state.list];
      const index = copyList.findIndex(item => item.id === actions.payload.id);
      if (index !== -1) {
        copyList[index].num = actions.payload.num + 1;
      } else {
        copyList.push(actions.payload)
      }
      state.list = copyList;
      sessionStorage.setItem('list', JSON.stringify(copyList));
    },
    adds(state, actions) {
      const copyJilu = [...state.jilu]
      const id = copyJilu.findIndex(item => item === actions.payload)
      if (id != -1) {
        copyJilu.splice(id, 1)
        copyJilu.unshift(actions.payload)
      } else {
        copyJilu.unshift(actions.payload)
      }
      state.jilu = copyJilu
      sessionStorage.setItem('jilu', JSON.stringify(copyJilu))
    },
    dels(state) {
      state.jilu = []
      sessionStorage.setItem('jilu', JSON.stringify([]))
    },
    del(state, actions) {
      const copyJilu = [...state.jilu]
      const id = copyJilu.findIndex(item => item === actions.payload)
      copyJilu.splice(id, 1)
      state.jilu = copyJilu
      sessionStorage.setItem('jilu', JSON.stringify(copyJilu))
    },
    // 删除选中商品（接收选中的ID数组）
    deleteSelectedItems(state, action) {
      const selectedIds = action.payload;
      const remainingItems = state.list.filter(item => !selectedIds.includes(item.id));
      state.list = remainingItems;
      sessionStorage.setItem('list', JSON.stringify(remainingItems));
    }
  }
})

export const { addgwc, adds, dels, del, deleteSelectedItems, addj } = login.actions;
export default login.reducer;